import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { AcquisitionManageContext, IAcquisitionActionEnum } from '../mconfig';
import { materialTableService } from '../services/UpdateTableService';
import { materialTableConfig } from '../mconfig';
import { Col, Row, message } from 'antd';
import { getColorTextLoadMap, getKeyRouter, getLoadMapList, getSelectDataMapList, getTenantID, onCloseModalCommon } from '@/utils';
import { showTotalInfo } from '@/common/constVariable';
import { OpenMaterialType } from './OpenMaterialType';
import { UpdateTableCommon } from './UpdateTableCommon';
import { ILoadMapTypeAll } from '@/common';
import { AssetAcquisitionManageAPI } from '../common/type';
import { getStoreTypeManage } from '../services/ManageTreeServices';

export const OpenMaterialModal: React.FC<AssetAcquisitionManageAPI.IOpenMaterialModal> = ({ onClose, isShowModal }) => {
  /**弹框的ref*/
  const updateModalRef: Ref<IOneModalRef> = useRef(null);
  const styleFixCls = 'contract-styfixcls-';
  // /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
  ]);
  // /** 资产类型 */
  const assetTypeList = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`], 'name', 'id', true);

  /** 获取上下文 */
  const {
    materielList,
    contractList, // 选择的合同
    purchaseList, // 选择的采购申请
    contractForm, // 表单form
    contractMaterList,
    addMatrielList,
    curRes,
    rightTableProps: { materielForm },
    acquisitionDispatch,
  } = useContext(AcquisitionManageContext);
  // 组装参数
  const matrielParams = {
    contractID: contractList[0]?.id || '', // 合同id
    applyID: purchaseList[0]?.applyID, // 采购申请id
    storageType: '1', // 验收类型
  };
  /** 获取列表 */
  const { data, params, loading, pagination, searchList, loadMdicMapObj, getManageData } = materialTableService(curRes, matrielParams);
  /**
   *  获取左侧类型数据
   */
  const { reloadLeftTree, designTypeTree, designTypeLoading } = getStoreTypeManage(curRes);

  const dataRowMemo = useMemo(() => {
    let dataRow: Record<string, any>[] = [];
    // 添加总价和数量字段
    if (data?.rows?.length > 0) {
      data?.rows?.forEach((item: any) => {
        dataRow.push(item);
      });
    }
    // if (data?.rows?.length > 0) {
    //   data?.rows?.forEach((item: any) => {
    //     const formDetail: Record<string, any>[] = materielForm.getFieldValue('detailList')?.length > 0 ? materielForm.getFieldValue('detailList') : [];
    //     const itemInfo: Record<string, any> | any = formDetail?.find((itemForm: any) => itemForm?.materialID == item?.id);
    //     let info: Record<string, any> = {};
    //     if (itemInfo && JSON.stringify(itemInfo) != '{}') {
    //       info = {
    //         ...item,
    //         ...itemInfo,
    //         materialID: item?.id,
    //       };
    //     } else {
    //       info = {
    //         ...item,
    //         materialID: item?.id,
    //       };
    //     }
    //     delete info['id'];
    //     dataRow?.push(info);
    //   });
    // }
    return dataRow;
  }, [data]);
  //data, materielForm.getFieldValue('detailList')

  /** 暂时保存选中的值 */
  const [checkMaterialList, setCheckMaterialList] = useState<Record<string, any>[]>([]);

  /** 选中树的key */
  const [selectKeys, setSelectKeys] = useState<React.Key[]>([]);

  /** 搜索 */
  const onSearch = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 重置 */
  const onReset = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 分页change 方法 */
  const onPageChange = (current: number, pageSize: number) => {
    getManageData({ ...params, current, pageSize });
  };

  /** 点击选中 */
  const onSelectTable = (selectInfo) => {
    setCheckMaterialList(selectInfo);
  };

  /** 初始化 */
  useEffect(() => {
    setCheckMaterialList(materielList);
  }, [isShowModal]);

  /** 点击确定 */
  const onSave = () => {
    if (checkMaterialList && checkMaterialList?.length > 0) {
      // materielForm.setFieldsValue({
      //   detailList: checkMaterialList,
      // });
      // acquisitionDispatch({
      //   type: IAcquisitionActionEnum.SELECT_ADD_MATRIEL,
      //   payload: checkMaterialList,
      // });

      // 添加类型   1 服务
      const newTempList = checkMaterialList.map((item) => {
        item.fuwu = '1';
        item.waiguan = 1;
        item.jishu = 1;
        return item;
      });

      // 存储到仓库
      acquisitionDispatch({
        type: IAcquisitionActionEnum.SELECT_MATERIEL,
        payload: [...newTempList],
      });
      onCloseModalCommon(updateModalRef);
    } else {
      message.error('请至少选择一个货物');
    }
    return;
  };

  /**左侧数据点击事件过滤数据*/
  const onSelectLeftTree = (val: string | null) => {
    if (val) {
      getManageData({ assetType: val });
    } else {
      getManageData({ assetType: null });
    }
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={updateModalRef}
        title={'货物列表'}
        onCancel={onClose}
        width={document.body.clientWidth * 0.65}
        bodyStyle={{
          height: document.body.clientHeight * 0.55,
          padding: 10,
        }}
        onOk={onSave}
      >
        {/* <Row className={`${styleFixCls}materialModal`}> */}
        {/* <Col span={6}>
            <OpenMaterialType
              onSelect={onSelectLeftTree}
              typeTreeLoading={designTypeLoading}
              typeTreeData={designTypeTree}
              onTreeKey={{ selectKeys, setSelectKeys }}
              loadMdicMapObj={loadMdicMapObj}
            />
          </Col> */}
        {/* <Col span={18}> */}
        <UpdateTableCommon
          styleFixCls={styleFixCls}
          searchProps={{
            searchList,
            onReset,
            onSearch,
          }}
          selectTablePorps={{
            onSelectTable,
            selectRowObjList: checkMaterialList,
            selectType: 'checkbox',
            setCheckRows: setCheckMaterialList,
          }}
          tableProps={{
            columns: materialTableConfig(assetTypeList),
            loading,
            dataSource: dataRowMemo,
            pagination,
            onPageChange,
            rowKey: 'id',
            tableTotalShow: (total: any, range: any) => {
              return (
                <div
                  style={{
                    display: 'flex',
                    width: '100%',
                    justifyContent: 'space-between',
                  }}
                >
                  <div>
                    已选择<strong style={{ color: 'red' }}> {checkMaterialList?.length} </strong>条货物
                  </div>
                  <div>{showTotalInfo(total, range)}</div>
                </div>
              );
            },
          }}
        />
        {/* </Col> */}
        {/* </Row> */}
      </OneModal>
    </>
  );
};
